package com.teng.service.impl;

import com.teng.exception.OAException;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.teng.dao.UserDao;
import com.teng.entity.UserEntity;
import com.teng.dto.UserContext;
import com.teng.service.UserService;
import com.teng.util.MD5;

public class UserServiceImpl implements UserService{

	@Override
	public UserContext login(String account, String password, String loginIp) throws Exception {
			//1验证清理参数
				if(account==null||(account=account.trim()).length()==0) {
					throw new OAException("账号不能为空");
				}
				
				if(password==null||(password=password.trim()).length()==0) {
					throw new OAException("密码不能为空");
				}
				if(account.length()>32) {
					throw new OAException("账号不存在");
				}
				//2执行业务逻辑
				//2.1账号是否存在
				UserDao udao=new UserDao();
				
				UserEntity u=udao.selectByAccount(account);
				
				if(u==null) {
					throw new OAException("帐号与密码不匹配");
				}
				if(!u.getPassword().equals(password)) {
					throw new OAException("帐号与密码不匹配");
				}
				if(u.getFlag()!=0) {
					throw new OAException("账号被锁定，请联系管理员");
				}
				
				//2.2更新登录ip和登录时间
				//Map<String,Object> map=new HashMap<>();
				//map.put("last_login_IP", loginIp);
				//map.put("last_login_time", new Date());
				//udao.update(u.getId(), map);
				//结果组装
				UserContext uc=new UserContext();
				uc.setAccount(account);
				uc.setAvatar(u.getAvatar());
				uc.setCreateTime(u.getCreateTime());
				uc.setCreateUserId(u.getCreateUser().getId());
				uc.setFlag(u.getFlag());
				uc.setId(u.getId());
				uc.setLastLoginIP(u.getLastLoginIP());
				uc.setLastLoginTime(u.getLastLoginTime());
				uc.setLastModifyPasswordTime(u.getLastModifyPasswordTime());
				uc.setName(u.getName());
				uc.setPhone(u.getPhone());
				uc.setRemark(u.getRemark());
				uc.setSecurityEmail(u.getSecurityEmail());
				return uc;
	}

	}

